package com.huanmeiqi.lucene.demo.ik;

import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;

public final class IKTokenizer4Lucene7 extends Tokenizer {

	// IK分词器实现
	private IKSegmenter _IKImplement;
	// 词元文本属性
	private final CharTermAttribute termAtt = (CharTermAttribute)this.addAttribute(CharTermAttribute.class);
	// 词元位移属性
	private final OffsetAttribute offsetAtt = (OffsetAttribute)this.addAttribute(OffsetAttribute.class);
	// 词元分类属性（该属性分类参考org.wltea.analyzer.core.Lexeme中的分类常量）
	private final TypeAttribute typeAtt = (TypeAttribute)this.addAttribute(TypeAttribute.class);
	// 记录最后一个词元的结束位置
	private int endPosition;

	/**
	 * @param useSmart
	 */
	public IKTokenizer4Lucene7(boolean useSmart) {
		super();
		this._IKImplement = new IKSegmenter(input, useSmart);
	}

	@Override
	public boolean incrementToken() throws IOException {
		// 清除所有的词元属性
		this.clearAttributes();
		Lexeme nextLexeme = this._IKImplement.next();
		if (nextLexeme != null) {
			// 将Lexeme转成Attributes
			// 设置词元文本
			this.termAtt.append(nextLexeme.getLexemeText());
			// 设置词元长度
			this.termAtt.setLength(nextLexeme.getLength());
			// 设置词元位移
			this.offsetAtt.setOffset(nextLexeme.getBeginPosition(),
					nextLexeme.getEndPosition());
			// 记录分词的最后位置
			this.endPosition = nextLexeme.getEndPosition();
			// 记录词元分类
			this.typeAtt.setType(nextLexeme.getLexemeTypeString());
			// 返会true告知还有下个词元
			return true;
		}
		// 返会false告知词元输出完毕
		return false;
	}

	@Override
	public void reset() throws IOException {
		super.reset();
		this._IKImplement.reset(this.input);
	}

	@Override
	public final void end() {
		// set final offset
		int finalOffset = correctOffset(this.endPosition);
		offsetAtt.setOffset(finalOffset, finalOffset);
	}
}
